// utils/grabOrder/grabOrder.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hours: '0' + 0, // 时
    minute: '0' + 0, // 分
    second: '0' + 0, // 秒
    time: "",
    newSecond: 0,
    newMinute: 0,
    newHour: 0,
    orderDetail: [],
    orderId: null,
    distance: null,
    mylat: null,
    mylng: null,
    lat: null,
    lng: null,
    publishId: 0,
    project: [],
    check: false,
    isShow: false,
    confirm: "确认",
    show: false,
    pageShow:true
  },


  isShow: function() {
    this.setData({
      isShow: !this.data.isShow
    })
  },


  /**
   *  确认抢单事件函数
   */
  confirm: function() {
    let that = this;
    if (that.data.check == false) {
      wx.showToast({
        title: '请先同意用户协议及隐私声明',
        duration: 3000,
        icon: "none"
      })
    } else {

      wx.showModal({
        title: '提示',
        content: '确认抢单',
        cancelText: '取消',
        confirmText: '确定',
        confirmColor: '#0bbd79',
        success: function(res) {
          if (res.confirm) {
            wx.request({
              url: 'https://www.xiaozheng8.com/serviceOrder/setStatus/v3',
              method: "post",
              data: {
                status: 4,
                publishId: that.data.publishId,
                userId: wx.getStorageSync("userId"),
                cateId: -1,
              },
              success: function(res) {
                console.log(res)
                that.setData({
                    status: 4,
                    orderId: res.data.data.orderId
                  }),
                  console.log(res)
                console.log(res.data.data.orderId)
                wx.setStorageSync("receiveCheck", true);
                that.setData({
                  confirm: "等待发单方确认"
                })
                // wx.navigateTo({
                //   url: '../confirmOrder/confirmOrder?orderId=' + that.data.orderId,
                // })
              },
            })

          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },

  map: function() {
    let that = this;
    console.log(that.data.publishId + 'zssss')
    wx.getSetting({
      success: (res) => {
        console.log(res);
        if (!res.authSetting['scope.userLocation'])
          app.openConfirm()
      }, fail(res) {
        console.log(res);
      }
    })
    wx.showLoading({
      title: '加载中',
    })
    // wx.showLoading({
    //   title: '加载中',
    //   success(res){
    //     that.setData({
    //       pageShow:false
    //     })
    //   }
    // })
    wx.request({
      url: 'https://www.xiaozheng8.com/serviceOrder/receiveFindById',
      method: "post",
      data: {
        publishId: that.data.publishId,
        userId: wx.getStorageSync("userId"),
      },
      success: function(res) {
        wx.getLocation({
          success: function (res) {
            wx.navigateTo({
              url: '../map/map?lat1=' + that.data.lat + "&lng1=" + that.data.lng + "&lat2=" + res.latitude + "&lng2=" + "&lng2=" + res.longitude,
            })
          },
        })
        // wx.getLocation({ //获取当前经纬度
        //   altitude: true,
        //   type: 'wgs84', //返回可以用于wx.openLocation的经纬度
        //   success: function(res) {
        //     wx.openLocation({ //​使用微信内置地图查看位置。
        //       latitude: that.data.lat, //要去的纬度-地址
        //       longitude: that.data.lng, //要去的经度-地址
        //     })
        //     wx.hideLoading(
        //     );
        //    setTimeout(()=>{
        //      that.setData({
        //        pageShow:true
        //      })
        //    })

           
          
        //     console.log("成功")
        //   }
        // })

      }

    })
  },
  // 如果上传了施工前图片，显示施工现场图片
  beforeWorkPic(publishId) {
    var that = this;
    wx.request({
      url: 'https://www.xiaozheng8.com/order/img/findByPublishId',
      data: {
        publishId: publishId
      },
      method: 'post',
      success: (res) => {
        console.log(res);
        that.setData({
          sceneImg: res.data.data
        })
      },
      fail: (res) => {
        console.log(res);
      },
      complete: () => { }
    });

  },
  // 等待时间
  time: function() {
    var that = this;
    var getTime = 0;
    console.log(this.data.publishId + "这是时间上的id2")
    wx.request({
      url: 'https://www.xiaozheng8.com/clock/get/grabTime',
      method: "post",

      data: {
        publishId: that.data.publishId,
        userId: wx.getStorageSync("userId")
      },

      success: function(res) {
        console.log(res)
        console.log(res.data.data);
        that.setData({
          newTime: res.data.data,

        })
        getTime = res.data.data;
        console.log(that.data.newTime + "时间")

        console.log(that.data.newTime + "计时器时间")

        var time = that.data.newTime;
        var second = time % 60;
        var minute = parseInt(time / 60);
        var hours = Math.floor(time / 60 / 60);
        that.setData({
          second: time % 60,
          minute: Math.floor(time / 60),
          hours: Math.floor(time / 60 / 60),
        });
        if (that.data.second < 10) {
          that.setData({
            second: "0" + that.data.second
          })
        }
        if (that.data.hours < 10) {
          that.setData({
            hours: "0" + that.data.hours
          })
        }
        if (that.data.minute < 10) {
          that.setData({
            minute: "0" + that.data.minute
          });
          if (Math.floor(time / 60 / 60) < 10) {
            that.setData({
              hours: '0' + Math.floor(time / 60 / 60)
            })
          } else {
            that.setData({
              hours: Math.floor(time / 60 / 60)
            })
          }
        }
        if (that.data.minute > 59) {
          that.setData({
            minute: Math.floor(time / 60) % 60
          });
          if (Math.floor(time / 60 / 60) < 10) {
            that.setData({
              hours: '0' + Math.floor(time / 60 / 60)
            })
          } else {
            that.setData({
              hours: Math.floor(time / 60 / 60)
            })
          }
        }
        that.setInterval = setInterval(function() {
          time++;
          if (time % 60 < 10) {
            that.setData({
              second: '0' + time % 60
            })
          } else {
            that.setData({
              second: time % 60
            })
          }
          if (parseInt(time / 60) % 60 < 10) {
            that.setData({
              minute: '0' + Math.floor(time / 60) % 60
            });

            if (Math.floor(time / 60 / 60) < 10) {
              that.setData({
                hours: '0' + Math.floor(time / 60 / 60)
              })
            } else {
              that.setData({
                hours: Math.floor(time / 60 / 60)
              })
            }
          } else {
            that.setData({
              minute: Math.floor(time / 60) % 60,

            });

            if (Math.floor(time / 60 / 60) < 10) {
              that.setData({
                hours: '0' + Math.floor(time / 60 / 60)
              })
            } else {
              that.setData({
                hours: Math.floor(time / 60 / 60)
              })
            }

            console.log(parseInt(time / 60 / 60));
            console.log(that.data.hours);

          }
        }, 1000)
      }
    });
  },
  // 预览图片
  imgPreview: function (e) {
    let img = e.currentTarget.dataset.src;
    console.log(img)
    wx.previewImage({
      urls: [img],
    })
  },
  /**
   * 取消按钮
   */
  cancel: function() {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '您确定要放弃抢该订单',
      success: function(res) {
        if (res.confirm) {
          wx.request({
            url: 'https://www.xiaozheng8.com/serviceOrder/grabRecord/giveUp',
            data: {
              publishId: that.data.publishId,
              userId: wx.getStorageSync("userId")
            },
            method: 'post',
            success: function(res) {
              console.log(res);
            },
            fail: function(res) {},
            complete: function(res) {},
          })
          wx.navigateBack({
            delta: 1,
          })
        }
      }
    })

  },

  /**
   * 获取当前经纬度
   */
  getAddress: function() {
    /**
     * 获取当前位置
     */
    let that = this;

    wx.getLocation({
      type: 'wgs84',
      success(res) {
        that.setData({
          mylat: res.latitude,
          mylng: res.longitude
        })
        // console.log(that.data.lat)
        // console.log(that.data.lng)
      }
    })
  },

  // 点击用户协议
  check: function() {
    this.setData({
      check: !this.data.check
    })
  },
  protocol: function(e) {
    var protocol = e.currentTarget.dataset.protocol;
    wx.navigateTo({
      url: '../protocol/protocol?protocol=' + protocol,
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  // 返回
  back: function() {
    wx.navigateBack()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    if (wx.getStorageSync("receiveCheck") == "" || wx.getStorageSync("receiveCheck") == undefined) {

    } else {
      that.setData({
        check: true
      })
    }
    that.getAddress();
    that.setData({
      distance: options.distance,
      publishId: options.publishId
    })
    console.log(options);
    this.beforeWorkPic(options.publishId);
    wx.request({
      url: 'https://www.xiaozheng8.com/serviceOrder/receiveFindById',
      method: "post",
      data: {
        publishId: options.publishId,
        userId: wx.getStorageSync("userId"),
        status: 2,
      },
      success: function(res) {
        console.log(res.data.data)
        if (res.data.code == 200) {
          that.setData({
            orderDetail: [res.data.data],
            lng: res.data.data.lng,
            lat: res.data.data.lat,
            feeItemIds: res.data.data.feeItemIds,
            project: res.data.data.project,
            distance: res.data.data.distance,
            receiveUserIdArray: res.data.data.receiveUserIdArray
          })
        }
        if (options.grab != undefined && options.grabStatus != -1) {
          that.setData({
            confirm: "等待发单方确认",
          })
        } else if (options.grab != undefined && options.grabStatus == -1) {
          that.setData({
            confirm: "该订单已被抢"
          });
          // wx.showNavigationBarLoading()
          wx.showToast({
            title: '该订单已被抢',
            icon: "none",
            duration: 3000
          })
        }
        /**
         * 费用明细
         */
        let fee = res.data.data.feeItemIds;
        console.log(that.data.distance + "juli")
        that.data.feeItemIds = fee.split(" ");
        that.setData({
          feeItemIds: that.data.feeItemIds,
        })
        let distance = Math.round(that.data.distance / 1000)
        console.log(that.data.distance)
        that.setData({
          distance: distance
        })
      },
    });
    if (this.data.orderDetail.length == 0) {
      wx.showToast({
        title: '加载中',
        icon: 'loading',
        mask: true
      })
    }
    console.log(that.data.publishId);

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    console.log(this.data.publishId);
    this.time()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    clearInterval(this.setInterval);
    clearInterval(this.getData);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    var that = this;
    clearInterval(that.setInterval);
    clearInterval(this.getData);

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})